import React from "react";
import { Drawer, Form, Button, TreeSelect, message, Input, Icon, Switch, Radio, DatePicker, Col, Divider, Tag } from "antd";
import { connect } from "dva";
import SimilarQuestion from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/similarQuestion";
import styles from "./editingStyle.less";
import ApiOrSlotModal from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/apiOrSlotModal";
import ApiEdit from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/apiEdit";
import SlotEdit from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/slotEdit";
import moment from "moment";
import ApiAndSlot from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/apiAndSlot";
import RelatedKnowledgeTag from "@/utils/RelatedKnowledgeTag";
import HistoryList from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/historyList";
import Answer from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/answer";
import Similar from "@/modules/Similar";
import UserSession from "@/UserSession";
import { userTypeList } from '@/services/geographic';
import { knowledgerecommendquestiondeleteB } from "@/services/capacityStudy";
import { knowledgeQaInfo } from "@/services/knowledgemanagement";
import AnswerUtils from "@/utils/answerUtils/answerUtils";
import MoreAnswers from "@/utils/answerUtils/moreAnswers";
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';
import knowledgeHome from "@/services/knowledgeHome";
import { formatMessage } from 'umi-plugin-react/locale';
const { TreeNode } = TreeSelect;
const { TextArea } = Input;
let timer;

class EditingKnowledge extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			title: formatMessage({id:'knowledgeManagement.overview.editingKnowledge.addTitle'}),
			visible: false,
			isShowSecondDrawer: false,
			similarQuestions: [],
			stdQuestion: "",
			categoryList: [],
			categoryValue: "",
			qaId: "",
			shared: false,
			synchronous: false,
			disabled: false,
			apiData: {},
			slotData: [],
			apiAndSlotData: [],
			slotDetailArr: [],
			userTagList: [],
			isForever: true,
			form: "",
			to: "",
			knowledgeDisable: true,
			relatedVisible: false,
			relatedData: [],
			historyVisible: false,
			historyData: [],
			saveLoading: false,
			similarData: [],
			similarType: "1",
			similarlibData: [],
			sourceData: [],
			resultId: "",
			validityOfKnowledge: 1, //1：永久有效 0：自定义有效期
			validityFrom: moment().format("YYYY-MM-DD HH"),
			validityTo: moment().add(7, "days").format("YYYY-MM-DD HH"),
			addType: null, // 0 智能学习 1 聚类问题 2 推荐问题
			isSystem: true,
			knowledgeDetail: null,
			knowledgeTagList: [],
			relatedTagVisible: false,
			pageHeight: 0,
			isPageHeight: false,
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	componentWillUnmount() {
		timer && clearTimeout(timer);
		window.removeEventListener('resize', this.getPageHeight)
	}

	getPageHeight = () => {
		console.log(document.getElementById('color_tag_file')?.clientHeight);
		this.setState({ pageHeight: document.getElementById('color_tag_file')?.clientHeight - 32 })
	}

	fetchCategory() {
		const { dispatch, pathId, ifCapacity } = this.props;
		let url = "editingKnowledge/getCategoryKnowledge";
		let obj = { categoryId: pathId, };
		if (ifCapacity) {
			url = "editingKnowledge/getAiLearningKnowledge";
			obj = {}
		};
		dispatch({
			type: url,
			payload: obj,
			callback: (res) => {
				console.log(res);
				let tree = [];
				if (this.props.ifCapacity) {
					tree = res;
					this.setState({
						categoryList: tree,
						categoryValue: this.state.categoryValue ? this.state.categoryValue : tree && tree.length > 0 ? tree[0]?.id : null,
					});
				} else if (res && res[0]) {
					tree.push(res[0]);
					this.setState({
						categoryList: tree,
						categoryValue: this.state.categoryValue ? this.state.categoryValue : tree && tree.length > 0 ? tree[0]?.id : null,
					});
				}
			},
		});
	}

	showEditDrawerFromAmendantRecord = (basicQuestion, questions) => {
		this.fetchCategory();
		this.setState(
			{
				visible: true,
				title: formatMessage({id:'knowledgeManagement.overview.editingKnowledge.addTitle'}),
				stdQuestion: basicQuestion ? basicQuestion : "",
				// categoryValue:this.state.categoryList[0].children[0].id
			},
			() => {
				setTimeout(() => {
					this.SimilarQuestion.setStandQuestion(basicQuestion);
					this.SimilarQuestion.setQuestions(questions ? questions : []);
				}, 500);
			}
		);
	};

	showEditDrawer = (row, question, categoryId, questions, sourceData, resultId, type) => {
		// console.log(type, "=================", row);
		this.fetchCategory();
		timer = setTimeout(() => {
			this.getPageHeight()
		}, 500)
		window.addEventListener('resize', this.getPageHeight)
		if (row) {
			this.setState(
				{
					visible: true,
					title: formatMessage({id:'knowledgeManagement.overview.editingKnowledge.editTitle'}),
					qaId: row.id ? row.id : row._id,
					categoryValue: categoryId,
					addType: type,
				},
				() => {
					this.getKnowledgeDetail(row.id ? row.id : row._id);
					// this.getSimiliarQuestion(row.id ? row.id : row._id);
					// this.getStandQuestion(row.id ? row.id : row._id);
				}
			);
		} else if (questions) {
			this.setState(
				{
					visible: true,
					title: formatMessage({id:'knowledgeManagement.overview.editingKnowledge.addTitle'}),
					stdQuestion: questions[0],
					categoryValue: categoryId,
					sourceData: sourceData ? sourceData : [],
					resultId: resultId ? resultId : "",
					addType: type,
				},
				() => {
					questions.shift();
					setTimeout(() => {
						this.SimilarQuestion.setQuestions(questions);
					}, 500);
				}
			);
		} else {
			this.setState({
				visible: true,
				title: formatMessage({id:'knowledgeManagement.overview.editingKnowledge.addTitle'}),
				stdQuestion: question || "",
				categoryValue: categoryId,
				addType: type,
			});
		}
	};

	getStandQuestion = (id) => {
		const { dispatch } = this.props;
		dispatch({
			type: "editingKnowledge/fetchStandQuestion",
			payload: { id },
			callback: (res) => {
				this.SimilarQuestion.setStandQuestion(res.question);
			},
		});
	};

	getSimiliarQuestion = (id) => {
		const { dispatch } = this.props;
		dispatch({
			type: "editingKnowledge/fetchSimiliarQuestion",
			payload: { id, limit: 9999999, page: 1, search: "" },
			callback: (res) => {
				let similarQuestions = res.list.map((item) => item.question);
				this.setState({ similarQuestions, }, () => {
					this.SimilarQuestion.setQuestions(similarQuestions);
				});
			},
		});
	};

	getKnowledgeDetail = async (id) => {
		const { dispatch, urlPrefix, pathId } = this.props;
		console.log(UserSession.isSystemKnowledge());
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeQaInfo({ qaId: id });
			// console.log(res);
			let stateParam = {
				categoryValue: res.categoryId,
				knowledgeDisable: !res.disabled,
				relatedData: res.relQas ? res.relQas.map(item => {
					return { ...item, id: item.qaIdRel }
				}) : [],
				isForever: true,
				knowledgeDetail: res,
				isSystem: res.relateQaSource && res.relateQaSource == 1 ? false : true,
				apiAndSlotData: res.slotAndApi ? res.slotAndApi : [],
				slotData: res.slotList ? res.slotList : [],
			};
			//处理有效期相关参数
			let validityOfKnowledge = 1;
			let validityFrom = "";
			let validityTo = "";
			//若存在有效期开始时间和结束时间 则选项为自定义有效期且对有效期时间段赋值 否则选项为永久有效 不对有效期时间赋值
			if (res.activeTimeStart && res.activeTimeEnd) {
				validityOfKnowledge = 0;
				validityFrom = moment(res.activeTimeStart).format("YYYY-MM-DD HH");
				validityTo = moment(res.activeTimeEnd).format("YYYY-MM-DD HH");
				stateParam.validityFrom = validityFrom;
				stateParam.validityTo = validityTo;
			};
			stateParam.validityOfKnowledge = validityOfKnowledge;
			this.setState({ ...stateParam }, () => {
				this.RelatedKnowledge.setRelatedList(res.relQas ? res.relQas.map(item => {
					return { ...item, id: item.qaIdRel }
				}) : []);
				// this.Answer.setAnswer({
				// 	robotAnswers: res.answers,
				// 	answersHeadquarters: res.answersHeadquarters,
				// 	answerSource: res.answerSource
				// });

				//v2版本答案改版
				this.AnswerUtils.setAnswers(res.answers.defaultAnswer)
				this.MoreAnswers.setAnswersFromDetail(res.answers.answers)

				this.SimilarQuestion.setStandQuestion(res.basicQuestion);
				this.SimilarQuestion.setQuestions(res.questions ? res.questions : []);
				if (res.apiId) {
					this.setApiData({ id: res.apiId });
				}
			});
		} else {
			dispatch({
				type: "editingKnowledge/fetchKnowledgeDetail",
				payload: { id, urlPrefix: UserSession.isSystemKnowledge() ? 1 : null },
				callback: (res) => {
					console.log(res);
					let stateParam = {
						categoryValue: res.categoryId,
						knowledgeDisable: !res.disabled,
						relatedData: res.relQas ? res.relQas.map(item => {
							return { ...item, id: item.qaIdRel }
						}) : [],
						isForever: true,
						knowledgeDetail: res,
						isSystem: res.relateQaSource && res.relateQaSource == 1 ? false : true,
						apiAndSlotData: res.slotAndApi ? res.slotAndApi : [],
						slotData: res.slotList ? res.slotList : [],
					};
					//处理有效期相关参数
					let validityOfKnowledge = 1;
					let validityFrom = "";
					let validityTo = "";
					//若存在有效期开始时间和结束时间 则选项为自定义有效期且对有效期时间段赋值 否则选项为永久有效 不对有效期时间赋值
					if (res.activeTimeStart && res.activeTimeEnd) {
						validityOfKnowledge = 0;
						validityFrom = moment(res.activeTimeStart).format("YYYY-MM-DD HH");
						validityTo = moment(res.activeTimeEnd).format("YYYY-MM-DD HH");
						stateParam.validityFrom = validityFrom;
						stateParam.validityTo = validityTo;
					};
					stateParam.validityOfKnowledge = validityOfKnowledge;

					let knowledgeTagList = [];
					if (res.knowledgeTagList && res.knowledgeTagList.length) {
						res.knowledgeTagList.forEach(item => {
							if (item.tagList && item.tagList.length > 0){
								item.tagList.forEach(i => {
									knowledgeTagList.push({ color: item.tagColor, id: i.id, name: i.tagValue })
								})
							}
						});
					};
					this.setState({ ...stateParam, knowledgeTagList }, () => {
						this.RelatedKnowledge.setRelatedList(res.relQas ? res.relQas.map(item => {
							return { ...item, id: item.qaIdRel }
						}) : []);
						// this.Answer.setAnswer({
						// 	robotAnswers: res.answers,
						// 	answersHeadquarters: res.answersHeadquarters,
						// 	answerSource: res.answerSource
						// });

						//v2版本答案改版
						this.AnswerUtils.setAnswers(res.answers.defaultAnswer)
						this.MoreAnswers.setAnswersFromDetail(res.answers.answers)

						this.SimilarQuestion.setStandQuestion(res.basicQuestion);
						this.SimilarQuestion.setQuestions(res.questions ? res.questions : []);
						if (res.apiId) {
							this.setApiData({ id: res.apiId });
						}
					});
				},
			});
		}
	};

	onClose = () => {
		this.AnswerUtils.clearInitData()
		this.setState({
			visible: false,
			similarQuestions: [],
			qaId: "",
			categoryValue: "",
			categoryList: [],
			relatedData: [],
			isForever: true,
			from: "",
			to: "",
			knowledgeDisable: true,
			slotData: [],
			apiAndSlotData: [],
			slotDetailArr: [],
			apiData: {},
			similarType: 1,
			similarData: [],
			similarlibData: [],
			validityOfKnowledge: 1, //1：永久有效 0：自定义有效期
			validityFrom: moment().format("YYYY-MM-DD HH"),
			validityTo: moment().add(7, "days").format("YYYY-MM-DD HH"),
			addType: null,
			knowledgeTagList: [],
			relatedTagVisible: false,
		});
	};

	showMoreQuestionDrawer = (similarQuestions, stdQuestion) => {
		this.setState({
			isShowSecondDrawer: true,
			similarQuestions,
			stdQuestion,
		});
	};

	closeMoreQuestionDrawer = () => {
		let data = this.SimilarQuestionMore.state.moreQuestions;
		let stdQuestion = this.SimilarQuestionMore.getStdQuestionForSecondDrawer();
		this.setState({ similarQuestions: data, isShowSecondDrawer: false, }, () => {
			this.SimilarQuestion.setQuestions(data);
			this.SimilarQuestion.setStandQuestion(stdQuestion);
		});
	};

	onChangeCategory = (value) => {
		// console.log(value);
		this.setState({ categoryValue: value, });
	};

	onSubmit = async () => {
		const that = this;
		const questionObj = that.SimilarQuestion.submitQuestions();
		const {
			categoryList, categoryValue, qaId, disabled, apiData, isForever, slotData, apiAndSlotData, from, to,
			knowledgeDisable, relatedData, resultId, validityFrom, validityTo, validityOfKnowledge, addType, knowledgeTagList,
		} = that.state;
		const { dispatch, answerRecordsId, form } = that.props;
		// const answers = this.Answer.getAnswers();
		// const answerSource = this.Answer.state.isSystem ? 0 : 1;
		// for (const robotItem of answers) {
		// 	for (const answerItem of robotItem.answers) {
		// 		//json答案 判断json是否合法
		// 		if (answerItem.answerType && answerItem.answerType === "json" && !answerItem.jsonResult.flag) {
		// 			message.error(`${robotItem.robotName}${formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.jsonAnswerIn' })},${answerItem.jsonResult.msg}`);
		// 			that.setState({ saveLoading: false, });
		// 			return false;
		// 		}
		// 		//富文本答案(没有answerType字段或者answerType不为json) 判断内容不能为空
		// 		if ((answerItem.answerType != "json" || !answerItem.answerType) && !answerItem.content) {
		// 			message.error(`${robotItem.robotName}${formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.answerCannotBeEmpty' })}`);
		// 			that.setState({ saveLoading: false, });
		// 			return false;
		// 		}
		// 		if (answerItem.question == null) {
		// 			answerItem.contentId = undefined;
		// 		}
		// 	}
		// }

		//v2版本答案改版
		let answers = {}
		const answerResult = await this.AnswerUtils.getAnswerResult();
		console.log(answerResult);
		if (answerResult.flag) {
			answers.defaultAnswer = { ...answerResult.result, isDefault: true };
		} else {
			if (answerResult.message) {
				message.error(answerResult.message);
			};
			return false;
		};
		const answerList = this.MoreAnswers.dealtWithAnswers();
		answers.answers = answerList.map(item => ({ ...item, isDefault: false }));

		this.setState({ saveLoading: true, });

		if (!questionObj.stdQuestion) {
			that.setState({ saveLoading: false, });
			return false;
		};

		const slots = slotData.map((item) => item.id);
		const relateQAs = relatedData.map((item) => item.id);

		//处理生效时间
		let validity = 99;
		if (validityOfKnowledge === 0) {
			const today = moment().format("YYYY-MM-DD HH");
			//选择的开始日期在当前日期之前
			let isFromBefore = moment(validityFrom).isBefore(today);
			let isToBefore = moment(validityTo).isBefore(today);

			if (isFromBefore) {
				//选择的开始日期在当前日期之前 则判断结束日期是否在当前日期之前，若是，则过期 若不是，则生效
				if (isToBefore) {
					validity = 2;
				} else {
					validity = 0;
				}
			} else {
				//选择的开始日期在当前日期之后或者等于 等于则生效 之后则未生效 无需判断选择的结束日期
				if (validityFrom === today) {
					validity = 0;
				} else {
					validity = 1;
				}
			}
		};

		let url = "editingKnowledge/doSave";
		let obj = {
			relateQAs: relateQAs,
			categoryId: categoryValue,
			answers,
			answerSource: 1,
			questions: questionObj.questions, //相似问
			basicQuestion: questionObj.stdQuestion, //标准问
			// isSharedQA: false,
			disabled: !knowledgeDisable,
			// isForever: isForever,
			// qaId: '',
			// isNew: '',
			relateQaSource: this.state.isSystem ? null : 1,
			apiId: apiData.id ? apiData.id : "",
			slots: slots,
			slotAndApi: apiAndSlotData,
			type: slots.length > 0 ? 1 : 0, //0普通知识点  1词槽知识点
			validity,
			knowledgeTagList: knowledgeTagList.map(i => i.id),
		};
		if (validityOfKnowledge === 0) {
			obj.activeTimeStart = validityFrom;
			obj.activeTimeEnd = validityTo;
		};
		if (qaId) {
			obj.id = qaId;
			url = "editingKnowledge/doEdit";
		};
		if (addType == 0) {
			url = "editingKnowledge/addKnowledgeByCapacity";
		};

		if (addType == 1) {
			url = "editingKnowledge/addKnowledgeByCluster";
		};

		if (addType == 2) {
			url = "editingKnowledge/addKnowledgeByAuto";
		};

		dispatch({
			type: url,
			payload: obj,
			callback: (res) => {
				if (res.code && res.code != 0) {
					that.setState({ saveLoading: false, });
				} else {
					if (answerRecordsId && res.status) {
						that.props.updateResolvedStatus();
					};
					that.setState({ saveLoading: false, });
					message.info(res.msg);
					if (that.props.refreshList) {
						that.props.refreshList("done");
					};
					if (resultId) {
						this.delQuestion();
					};
					that.onClose();
				}
			},
		});
	};

	/**
	 *Api/slot
	 */
	openListModal = (type) => {
		this.ApiOrSlotModal.initData(type);
	};

	setApiData = (data) => {
		// console.log(data);
		const { dispatch, pathId } = this.props;
		let obj = {};
		dispatch({
			type: "editingKnowledge/doApiDetailById",
			payload: { id: data.id, urlPrefix: pathId ? 1 : null },
			callback: (res) => {
				// console.log(res);
				if (res) {
					obj = res;
					this.setState({ apiData: obj, });
				}
			},
		});
	};

	removeApi = () => {
		this.setState({ apiData: {}, apiAndSlotData: [], });
	};

	setSlotData = (data) => {
		// console.log(data);
		let { slotData } = this.state;
		let result = slotData.some((item) => {
			if (item.id === data.id) {
				return true;
			}
		});
		if (result) {
			return message.error(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.slotAlreadySelected' }));
		};
		// //判断当前选择的词槽是不是第一个 若是 则默认答案从编辑框转变为预览状态 需要保存一下答案 若不是 则不作其他操作
		// if (slotData.length === 0) {
		// 	// console.log(slotData);
		// 	this.Answer.getAnswers("setSlotData");
		// };
		data.key = data.keyName;
		slotData.push(data);
		this.setState({ slotData, });
	};

	removeSlot = (data) => {
		let { slotData, apiAndSlotData } = this.state;
		let arr = slotData.filter((item) => item.id != data.id);
		let apiAndSlot = apiAndSlotData.filter((item) => item.slotKey != (data.key ? data.key : data.keyName));
		this.setState({ slotData: arr, apiAndSlotData: apiAndSlot }, () => {
			//删除一个词槽，则需要同步删除所有词槽答案中的该词槽选项
			this.MoreAnswers.removeSlotForOneOfAnswer(data)
			// if (arr.length === 0) {
			// 	// 当词槽全部删除时，去掉所有词槽答案
			// 	// this.Answer.removeSlotAnswer();
			//   this.MoreAnswers.removeSlotForAllAnswer()
			// }
		});
	};

	addSlotApiRelations = () => {
		let { apiAndSlotData } = this.state;
		const newData = { slotKey: "", apiFieldId: "", };
		this.setState({ apiAndSlotData: [...apiAndSlotData, newData], });
	};

	fixRelationData = (e, record, index, type) => {
		let { apiAndSlotData } = this.state;
		for (const i in apiAndSlotData) {
			if (i == index) {
				switch (type) {
					case "api":
						apiAndSlotData[i].apiFieldId = e;
						break;
					case "slot":
						apiAndSlotData[i].slotKey = e;
						break;
				}
			}
		};
		this.setState({ apiAndSlotData, });
	};

	removeSlotApiRelations = (index) => {
		let { apiAndSlotData } = this.state;
		const arr = apiAndSlotData.filter((item, i) => i != index);
		this.setState({ apiAndSlotData: arr, });
	};

	addSlotAnswer = (openType, answerIndex) => {
		const { slotData } = this.state;
		if (slotData && slotData.length > 0) {
			let ids = slotData.map((item) => item.id);
			this.getSlotDetailById(ids, openType, answerIndex);
		} else {
			this.getUserTagList(openType, answerIndex);
		}
	};

	getSlotDetailById = (ids, openType, answerIndex) => {
		const { dispatch, urlPrefix, pathId } = this.props;
		const that = this;
		dispatch({
			type: "editingKnowledge/getSlotDetail",
			payload: { ids },
			callback: (res) => {
				that.setState({ slotDetailArr: res }, () => this.getUserTagList(openType, answerIndex));
			},
		});
	};

	/* 获取用户类型-筛选框 */
	getUserTagList = async (openType, answerIndex) => {
		const res = await userTypeList({ current: 1, size: 999999 });
		this.setState({ userTagList: res.records ? res.records : [], }, () => {
			switch (openType) {
				case "add":
					this.Answer.openAddAnswer();
					break;
				case "edit":
					this.Answer.openEditAnswer(answerIndex);
					break;
			}
		});
	};

	changeKnowledgeDisable = (value) => {
		this.setState({ knowledgeDisable: value, });
	};

	/**
	 * 关联知识标签
	 * @param data
	 * @returns {*}
	 */
	openRelatedKnowledgeTagModal = () => {
		let { knowledgeTagList } = this.state;
		this.RelatedKnowledgeTag.getList(knowledgeTagList);
		this.setState({ relatedTagVisible: true, });
	};

	closeRelatedTagModal = () => {
		this.setState({ relatedTagVisible: false, });
	};

	getRelatedTagList = (data) => {
		this.setState({ knowledgeTagList: data, });
	};

	removeRelatedTagData = (tag) => {
		let { knowledgeTagList } = this.state;
		const newData = knowledgeTagList.filter(item => item != tag);
		this.setState({ knowledgeTagList: newData });
	};

	// upRelatedData = (index) => {
	// 	const arr = this.state.relatedData;
	// 	if (index !== 0) {
	// 		arr[index] = arr.splice(index - 1, 1, arr[index])[0];
	// 	} else {
	// 		arr.push(arr.shift());
	// 	};
	// 	this.setState({ relatedData: arr });
	// };

	/**
	 * 关联知识点
	 * @param data
	 * @returns {*}
	 */

	openRelatedKnowledgeModal = () => {
		const { relatedData } = this.state;
    console.log(relatedData);
    this.RelatedKnowledge.openAndInit(relatedData)
	};

	closeRelatedModal = () => {
		this.setState({ relatedVisible: false, });
	};

	getRelatedList = (data, type) => {
		if (type === 'Add') {
			knowledgeHome.postQaRelAdd()
		}
		if (type === 'Del') {
			knowledgeHome.postQaRelDel()
		}
		// console.log(data);
		this.setState({ relatedData: data, });
	};

	removeRelatedData = (id) => {
		let { relatedData } = this.state;
		const newData = relatedData.filter((item) => item.id != id);
		knowledgeHome.postQaRelDel();
		this.setState({ relatedData: newData, }, () => {
			this.RelatedKnowledge.setRelatedList(newData);
		});
	};

	upRelatedData = (index) => {
		const arr = this.state.relatedData;
		if (index !== 0) {
			arr[index] = arr.splice(index - 1, 1, arr[index])[0];
		} else {
			arr.push(arr.shift());
		};
		this.setState({ relatedData: arr });
	};

	/**
	 * 历史记录
	 * @param data
	 * @returns {*}
	 */

	openHistory = () => {
		this.setState({ historyVisible: true, }, () => {
			this.getHistoryList();
		});
	};

	closeHistory = () => {
		this.setState({
			historyData: [],
			historyVisible: false,
		});
	};

	getHistoryList = () => {
		const { dispatch, currentUser } = this.props;
		const { qaId, historyQuery } = this.state;
		dispatch({
			type: "editingKnowledge/fetchHistoryByQaId",
			payload: { qaQuery: qaId, current: 1, size: 9999999, userQuery: "" },
			callback: (res) => {
				this.setState({ historyData: res.records, });
			},
		});
	};

	renderTree = (data) => {
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode title={item.name} key={item.id} value={item.id} id={item.id}>{this.renderTree(item.children)}</TreeNode>
				);
			};
			return (
				<TreeNode title={item.name} key={item.id} value={item.id} id={item.id} />
			);
		});
	};

	closeSimilar = (data, type) => {
		let { similarType, similarData, similarlibData } = this.state;
		similarType = type;
		let arr = [];
		data.map((item) => {
			arr.push(item.question);
		});
		if (type == "2") {
			similarlibData = data;
		} else {
			similarData = data;
		};
		this.setState({ similarData, similarType, similarlibData, }, () => {
			if (this.SimilarQuestion && this.SimilarQuestion.pushSimilarQuestion) {
				this.SimilarQuestion.pushSimilarQuestion(arr, data);
			};
			if (this.SimilarQuestionMore && this.SimilarQuestionMore.pushSimilarQuestion) {
				this.SimilarQuestionMore.pushSimilarQuestion(arr, data);
			}
		});
	};

	delQuestion = async () => {
		const questionObj = this.SimilarQuestion.submitQuestions();
		const { sourceData, resultId } = this.state;
		const arr = [...questionObj.questions, questionObj.stdQuestion];
		const questions = sourceData.filter((item) => arr.indexOf(item.question) > -1).map((items) => items.question);
		const res = await knowledgerecommendquestiondeleteB({ questions, resultId, });
		console.log(res);
	};

	onChangeQaIsForever = (e) => {
		this.setState({ validityOfKnowledge: e.target.value, });
	};

	changeTime = (value, dateString) => {
		this.setState({
			validityFrom: dateString[0],
			validityTo: dateString[1],
		});
	};

	changeTimeDone = (value) => {
		this.setState({
			validityFrom: value[0].format("YYYY-MM-DD HH"),
			validityTo: value[1].format("YYYY-MM-DD HH"),
		});
	};

	similarExtensionAsk = (data) => {
		if (this.SimilarQuestion) {
			this.SimilarQuestion.similarExtensionAsk(data)
		};
		if (this.SimilarQuestionMore) {
			this.SimilarQuestionMore.similarExtensionAsk(data)
		};
	}

	render() {
		const {
			visible, title, isShowSecondDrawer, similarQuestions, categoryList, categoryValue, stdQuestion,
			apiData, slotData, apiAndSlotData, slotDetailArr, isForever, knowledgeDisable, relatedVisible,
			relatedData, from, to, historyData, historyVisible, qaId, saveLoading, validityOfKnowledge,
			validityFrom, validityTo, isSystem, knowledgeDetail, userTagList, knowledgeTagList, relatedTagVisible,
			pageHeight, isPageHeight
		} = this.state;
		const { authority, urlPrefix, pathId, form } = this.props;

		return (
			<Drawer
				title={title}
				placement='right'
				closable
				onClose={this.onClose}
				visible={visible}
				width={800}
				headerStyle={{ background: "#F7F9FD", }}
				destroyOnClose
				bodyStyle={{ padding: '24px 0' }}
			>
				<div style={{ textAlign: "right", padding: '0 24px' }}>
					{/* <span style={{ marginRight: 10, cursor: 'pointer' }} onClick={this.openHistory}> */}
					{/*  <Icon type="clock-circle" theme="twoTone" style={{ marginRight: 5 }} /> */}
					{/*  历史 */}
					{/* </span> */}
					{urlPrefix ? null : (
						<Button style={{ marginRight: 10, backgroundColor: "#ffffff", color: '#3E5BFF', borderColor: '#6478FF', borderRadius: '16px' }} onClick={() => this.openListModal("api")}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addApi' })}</Button>
					)}

					{/* {urlPrefix ? null : (
						<Button style={{ backgroundColor: "#ffffff", color: '#3E5BFF', borderColor: '#6478FF', borderRadius: '16px' }} onClick={() => this.openListModal("slot")}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addSlot' })}</Button>
					)} */}
				</div>
				<div style={{ padding: '0 24px' }}>
					{slotData && slotData.length > 0 ? (
						<div style={{ margin: "10px 0px" }}>
							<h4 className={styles.hTitle}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.slotTitle' })}</h4>
							<SlotEdit data={slotData} removeSlot={this.removeSlot} urlPrefix={urlPrefix} />
						</div>
					) : ("")}
				</div>
				{slotData && slotData.length > 0 ? <Divider /> : null}

				<div style={{ padding: '0 24px' }}>
					{apiData && Object.keys(apiData).length > 0 ? (
						<div style={{ margin: "10px 0px" }}>
							<h4 className={styles.hTitle}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.apiInterface' })}</h4>
							<ApiEdit data={apiData} removeApi={this.removeApi} openListModal={this.openListModal} urlPrefix={urlPrefix} />
							{apiData && slotData && slotData.length > 0 && Object.keys(apiData).length > 0 ? (
								<ApiAndSlot
									slotData={slotData}
									apiData={apiData}
									apiAndSlotData={apiAndSlotData}
									addSlotApiRelations={this.addSlotApiRelations}
									fixRelationData={this.fixRelationData}
									removeSlotApiRelations={this.removeSlotApiRelations}
									urlPrefix={urlPrefix}
								/>
							) : ("")}
						</div>
					) : ("")}
				</div>

				<Divider />
				<div style={{ padding: '0 24px' }}>
					<h4 className={styles.hTitle} style={{ marginBottom: 20 }}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.questionTitle' })}</h4>
					<SimilarQuestion
						showMoreQuestion={this.showMoreQuestionDrawer}
						secondDrawer={isShowSecondDrawer}
						similarQuestionsList={similarQuestions}
						onRef={(ref) => (this.SimilarQuestion = ref)}
						stdQuestion={stdQuestion}
						authority={authority}
						slotData={slotData}
						similarRef={this.similarRef}
						questionId={qaId}
						urlPrefix={urlPrefix}
					/>
				</div>
				<Divider />
				<div style={{ padding: '0 24px' }}>
					<h4 className={styles.hTitle}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.answerTitle' })}</h4>
					<div style={{ width: 720, margin: "0 auto", marginBottom: 10 }}>
						{/*{*/}
						{/*  slotData.length > 0 ?*/}
						{/*    <div style={{textAlign:'right',margin:'10px 0'}}>*/}
						{/*      <Button onClick={() => this.addSlotAnswer('add')} type={'primary'}>添加答案</Button>*/}
						{/*    </div>*/}
						{/*    : ''*/}
						{/*}*/}
						{
							/**
							 * <Answer
									slotData={slotData}
									onRef={(ref) => (this.Answer = ref)}
									slotDetailArr={slotDetailArr}
									userTagList={userTagList}
									addSlotAnswer={this.addSlotAnswer}
									addActivePaneAnswer={() => this.addSlotAnswer("add")}
									urlPrefix={urlPrefix}
								/>
							 */
						}
						{/** 默认答案 */}
						<Form>
							<AnswerUtils form={form} onRef={ref => this.AnswerUtils = ref} hasRefer={true} />
						</Form>
						{/** 更多答案（个性化答案/词槽答案） */}
						<MoreAnswers onRef={ref => this.MoreAnswers = ref} slotData={slotData} />
					</div>
				</div>
				<Divider />
				<div style={{ padding: '0 24px' }}>
					<h4 className={styles.hTitle} style={{ overflow: "hidden", border: '0', padding: 0 }}>
						<Col span={12} style={{ padding: 0 }}><span style={{ borderLeft: '3px solid #3F4959', paddingLeft: '10px' }}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.relatedQuestionTitle' })}</span></Col>
						<Col span={12} style={{ textAlign: "right" }}>
							{UserSession.isSystemKnowledge() ? null : (
								<Button
									onClick={this.openRelatedKnowledgeModal}
									style={{ backgroundColor: "#ffffff", color: '#3E5BFF', borderColor: '#6478FF', borderRadius: '16px' }}
								>
									{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addRelatedKnowledge' })}
								</Button>
							)}
						</Col>
					</h4>
					<div style={{ margin: "0 auto", marginBottom: 10 }}>
						{relatedData.map((item, index) => {
							return (
								<div key={item.id} style={{ margin: "10px 0", position: 'relative' }}>
									{item.relateType === 1 ? (
										<span className={styles.reQaType}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.qaTypeQa' })}</span>
									) : item.relateType === 2 ? (
										<span className={styles.reQaType}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.qaTypeMindMap' })}</span>
									) : item.relateType === 3 ? (
										<span className={styles.reQaType}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.qaTypeMultiTurn' })}</span>
									) : item.relateType === 4 ? (
										<span className={styles.reQaType}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.qaTypeForm' })}</span>
									) : null}
									<div className={styles.relQaValue} title={item.basicQuestion}>
										{item.basicQuestion}
									</div>
									{UserSession.isSystemKnowledge() && isSystem ? null : (
										<Icon
											type='close-circle'
											style={{ margin: "0px 10px", fontSize: "20px", verticalAlign: 'middle' }}
											onClick={() => this.removeRelatedData(item.id)}
										/>
									)}
									{UserSession.isSystemKnowledge() && isSystem ? null : index != 0 ? (
										<span className={styles.relOptionUpBox}>
											<Icon
												type='arrow-up'
												style={{ fontSize: "12px" }}
												onClick={() => this.upRelatedData(index)}
											/>
										</span>
									) : null}
								</div>
							);
						})}
					</div>
				</div>
				<Divider />
				<div style={{ marginBottom: 10, padding: '0 24px' }}>
					<h4 className={styles.hTitle}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.knowledgeRelated' })}</h4>
					<div style={{ width: 700, margin: "0 auto" }}>
						<label>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.selectCategory' })}：</label>
						<TreeSelect
							style={{ width: "80%" }}
							dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
							placeholder={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.pleaseSelectCategory' })}
							allowClear
							showSearch
							showCheckedStrategy='SHOW_PARENT'
							treeNodeFilterProp='title'
							onChange={this.onChangeCategory}
							value={categoryValue ? categoryValue : categoryList[0]?.id}
							disabled={authority === 1 || urlPrefix}
						>
							{this.renderTree(categoryList)}
						</TreeSelect>

					</div>
				</div>
				{UserSession.isSystemDataKnowledge() ? null : (
					<>
						<Divider />
						<div style={{ padding: '0 24px' }}>
							<h4 className={styles.hTitle}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.statusSettings' })}</h4>
							<div style={{ marginTop: 24 }}>
								<label>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.knowledgeStatus' })}：</label>
								<Switch
									checkedChildren={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.enable' })}
									unCheckedChildren={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.disable' })}
									checked={knowledgeDisable}
									onChange={this.changeKnowledgeDisable}
									disabled={UserSession.isSystemKnowledge()}
								/>
							</div>
						</div>
					</>
				)}
				<div style={{ marginBottom: 60 }}>
					{/*<h4 className={styles.hTitle}>生效时间</h4>*/}
					{/*<div style={{ width: 700, margin: '0 auto' }}>*/}
					{/*  <div>*/}
					{/*    <label>知识点有效期：</label>*/}
					{/*    <Radio.Group onChange={this.onChangeQaIsForever} value={validityOfKnowledge}>*/}
					{/*      <Radio value={1}>永久有效</Radio>*/}
					{/*      <Radio value={0}>自定义有效期</Radio>*/}
					{/*    </Radio.Group>*/}
					{/*    {validityOfKnowledge === 0 ? (*/}
					{/*      <div style={{ marginTop: 20 }}>*/}
					{/*        <DatePicker.RangePicker*/}
					{/*          showTime={{ format: 'HH' }}*/}
					{/*          format="YYYY-MM-DD HH"*/}
					{/*          placeholder={['开始时间', '结束时间']}*/}
					{/*          onChange={this.changeTime}*/}
					{/*          onOk={this.changeTimeDone}*/}
					{/*          value={[moment(validityFrom), moment(validityTo)]}*/}
					{/*          allowClear={false}*/}
					{/*        />*/}
					{/*      </div>*/}
					{/*    ) : (*/}
					{/*      ''*/}
					{/*    )}*/}
					{/*  </div>*/}
					{/*</div>*/}
				</div>

				<Drawer
					title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.moreSimilarQuestion' })}
					placement='right'
					closable
					onClose={this.closeMoreQuestionDrawer}
					visible={isShowSecondDrawer}
					width={750}
					destroyOnClose
				>
					<SimilarQuestion
						showMoreQuestion={this.showMoreQuestionDrawer}
						secondDrawer={isShowSecondDrawer}
						similarQuestionsList={similarQuestions}
						stdQuestion={stdQuestion}
						onRef={(ref) => (this.SimilarQuestionMore = ref)}
						authority={authority}
						slotData={slotData}
						questionId={qaId}
						similarRef={this.similarRef}
					/>
				</Drawer>

				<ApiOrSlotModal
					onRef={(ref) => (this.ApiOrSlotModal = ref)}
					setApiData={this.setApiData}
					setSlotData={this.setSlotData}
				/>

				<HistoryList dataSource={historyData} visible={historyVisible} closeHistory={this.closeHistory} />

				<RelatedKnowledgeTag
					visible={relatedTagVisible}
					onClose={this.closeRelatedTagModal}
					getRelatedList={this.getRelatedTagList}
					onRef={(ref) => (this.RelatedKnowledgeTag = ref)}
				/>

        <RelatedKnowledgeV2 
          onRef={ref => this.RelatedKnowledge = ref}
          applicationId={''}
          chooseType='mutiple'
          getRelatedList={this.getRelatedList}
        />

				<div
					style={{
						position: "absolute",
						right: 0,
						bottom: 0,
						width: "100%",
						borderTop: "1px solid #e9e9e9",
						padding: "10px 16px",
						background: "#fff",
						textAlign: "right",
						zIndex: 99999999,
					}}
				>
					<Button onClick={this.onClose} style={{ marginRight: 8 }}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.cancel' })}</Button>
					<Button onClick={this.onSubmit} type='primary' disabled={authority === 1 || UserSession.isSystemKnowledge()} loading={saveLoading}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.confirm' })}</Button>
				</div>
				<Similar
					onRef={(ref) => (this.similarRef = ref)}
					questionId={qaId}
					onClose={this.closeSimilar}
					question={stdQuestion}
					similarExtensionAsk={this.similarExtensionAsk}
				/>
			</Drawer>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(EditingKnowledge));
